//
//  SearchDoctorsResultViewController.m
//  安好
//
//  Created by qinlongqing on 14/12/9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "SearchDoctorsResultViewController.h"
#import "ConsultDocListCell.h"
#import "DocInfoViewController.h"
#import "ConsultViewController.h"
#import "AppConfig.h"

@interface SearchDoctorsResultViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *mTableView;
    
    NSInteger page;
    NSInteger pageSize;
    
    UILabel *_hintLabel;

    NSMutableArray *doctorsArrays;
}
@end

@implementation SearchDoctorsResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    page = 1;
    pageSize = 10;
    
    self.view.backgroundColor = UIColorFromRGB(0xf2f2f2);
    
    doctorsArrays = [[NSMutableArray alloc]init];
    
    [self makeNavBar];
    
    [self createTableView];

    [self getDoctors];
}

-(void)makeNavBar{
    self.navigationItem.title = @"搜索结果";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

-(void)backBtnclicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createTableView{
    mTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    [mTableView addFooterWithTarget:self action:@selector(getDoctors)];
    [self.view addSubview:mTableView];
    
    _hintLabel = [[UILabel alloc] init];
    [mTableView.superview addSubview:_hintLabel];
    _hintLabel.text = @"没有更多了";
    _hintLabel.textAlignment=NSTextAlignmentCenter;
    _hintLabel.font = [UIFont systemFontOfSize:10];
    _hintLabel.textColor = [UIColor whiteColor];
    _hintLabel.backgroundColor = [UIColor blackColor];
    _hintLabel.layer.cornerRadius = 5;
    _hintLabel.layer.masksToBounds = YES;
    _hintLabel.alpha = 0;
    _hintLabel.frame = CGRectMake((mTableView.frame.size.width - 60) / 2, mTableView.frame.size.height + mTableView.frame.origin.y - 40, 60, 30);
}

- (void)getDoctors{
    if (page == 1) {
        [self showActionView];
    }
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",page],@"pagesize":[NSString stringWithFormat:@"%ld",pageSize],@"keyword":self.keyWords};
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetSearchResultURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [mTableView footerEndRefreshing];
        
        if (page == 1) {
            [self hiddenActionView];
        }
        
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            
        }
        else{
            NSInteger numbers = doctorsArrays.count;
            if ([[responseObject objectForKey:@"data"] count] != 0) {
                page +=1;
                [doctorsArrays addObjectsFromArray:[responseObject objectForKey:@"data"]];
            }
            if (numbers == doctorsArrays.count) {
                [UIView animateWithDuration:0.4f animations:^{
                    _hintLabel.alpha = 0.6;
                } completion:^(BOOL finished) {
                    if (finished) {
                        [UIView animateWithDuration:0.5 animations:^{
                            _hintLabel.alpha = 0;
                        }];
                    }
                }];
            }
            [mTableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [mTableView footerEndRefreshing];
        
        if (page == 1) {
            [self hiddenActionView];
        }
    }];
}


#pragma  mark UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return doctorsArrays.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *Indentifier=@"consultdocList";
    ConsultDocListCell *cell=[tableView dequeueReusableCellWithIdentifier:Indentifier];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"ConsultDocListCell" owner:self options:nil] lastObject];
        }
        else{
            cell=[[[NSBundle mainBundle]loadNibNamed:@"ConsultDocListCell" owner:self options:nil] firstObject];
        }
    }
    NSDictionary *doc=[doctorsArrays objectAtIndex:indexPath.row];
    [cell.docImage setImageWithURL:[NSURL URLWithString:[doc valueForKey:@"photourl"]] placeholderImage:nil];
    cell.docName.text=[doc valueForKey:@"username"];
    NSString *str;
    if ([[doc valueForKey:@"doclevelid"]  isEqualToString:@"0"]) {
        str=@"主任医师";
    }else if ([[doc valueForKey:@"doclevelid"] isEqualToString:@"1"])
    {
        str=@"副主任医师";
        
    }else if ([[doc valueForKey:@"doclevelid"] isEqualToString:@"2"]){
        str=@"主治医师";
    }
    else if ([[doc valueForKey:@"doclevelid"] isEqualToString:@"3"]){
        str=@"医师";
    }
    else{
        str=@"其他";
    }
    cell.docHospital.text=[NSString stringWithFormat:@"%@%@",[doc valueForKey:@"hospitalname"],str];
    cell.distance.text=[NSString stringWithFormat:@"%@m",[doc valueForKey:@"distance"]];
    cell.docExpert.text=[NSString stringWithFormat:@"擅长：%@",[doc valueForKey:@"expertise"]];
    if ([[NSString stringWithFormat:@"%@",[doc valueForKey:@"online"]] isEqualToString:@"1"]) {
        cell.onlineStatus.text=@"在线";
        cell.onlineImage.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#4fc1e9"];
    }else
    {
        cell.onlineStatus.text=@"离线";
        cell.onlineImage.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#717171"];
    }
    cell.docGood.text=[NSString stringWithFormat:@"赞（%@）",[doc valueForKey:@"good"]];
    cell.peerAuthor.text=[NSString stringWithFormat:@"同行认证（%@）",[doc valueForKey:@"good"]];
    cell.docFans.text=[NSString stringWithFormat:@"粉丝（%@）",[doc valueForKey:@"good"]];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma Mark UItableviewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 156.f;
    }
    else{
        return 130.f;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DocInfoViewController *docInfo=[[DocInfoViewController alloc]initWithNibName:@"DocInfoViewController" bundle:[NSBundle mainBundle]];
    docInfo.doctoruid=[[doctorsArrays objectAtIndex:indexPath.row] valueForKey:@"uid"];
    [self.navigationController pushViewController:docInfo animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
